using UnityEngine;
using System.Xml;
using System;
using EventBehaviorTree;
using BuffSystem;

public class BuffKeyGenerator : MonoBehaviour
{
    //void Start() { Gen_BuffKey(); }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.K)) { Gen_BuffKey(); }
    }

    private void Gen_BuffKey()
    {
        string xmlPath = Application.dataPath + "/StreamingAssets/Assets.xml";//relative path of XML file
        XmlDocument XMLDoc = new XmlDocument();
        XMLDoc.Load(xmlPath);
        #region Create buff key
        XmlNodeList xnListBuff = XMLDoc.SelectNodes("/Root/Buff");
        foreach (XmlNode xnBuffNode in xnListBuff) { Gen_XmlTaskNodeKey(xnBuffNode); }//the first functionNode of buff
        XMLDoc.Save(xmlPath);
        Debug.Log("BuffKey Generated");
        #endregion
    }
    /// <summary>
    /// generate rootNode key
    /// </summary>
    /// <param name="xnBuffNode">whose firstChild is the rootNode</param>
    private void Gen_XmlTaskNodeKey(XmlNode xnBuffNode) { Gen_XmlTaskNodeKey(xnBuffNode.FirstChild, null, true, xnBuffNode.Attributes[XMLAttri.BuffName].Value); }
    private void Gen_XmlTaskNodeKey(XmlNode xnBTFunction, Container parentNode) { Gen_XmlTaskNodeKey(xnBTFunction, parentNode, false, null); }
    private void Gen_XmlTaskNodeKey(XmlNode xnBTFunction, Container parentNode, bool isRootNode, string key)
    {
        Container formalNode = new Container();//to simplify the process, set all the node Container in case the node has subNodes
        if (!isRootNode) { parentNode.AddSubNodes(formalNode); }//get key for the node itself
        else { formalNode.SetKey(key); }
        NodeType nodeType = (NodeType)Enum.Parse(typeof(NodeType), xnBTFunction.Name);
        switch (nodeType)//container get subNode
        {
            case NodeType.Sequencer:
            case NodeType.Selector:
            case NodeType.TimerSequencer:
            case NodeType.ConditionSequencer:
                foreach (XmlNode child in xnBTFunction.ChildNodes) { Gen_XmlTaskNodeKey(child, formalNode); }//generate subNodes
                break;
            default:
                break;
        }
        if (nodeType == NodeType.TaskNode)//generate occuantKey
        {
            ComponentType componentType = (ComponentType)Enum.Parse(typeof(ComponentType), xnBTFunction.Attributes[XMLAttri.ComponentType].Value);
            if (componentType == ComponentType.Register && xnBTFunction.Attributes[XMLAttri.OccupantKey] == null)//is non-buff-register
            {
                xnBTFunction.Attributes[XMLAttri.NodeKey].Value = formalNode._key;
            }
        }
    }
}
